#!/usr/bin/env perl

use SBG::DomainIO::cofm;

#read in path to cofm-files
my $pathCofm = "./";
if(scalar(@ARGV) == 0){
	die "\n Provide path to cofm-files as argument \n e.g.: cofmToCandidates.pl ./cofm/ \n \n";
} else {
	$pathCofm = $ARGV[0];
}

my %pdbIDs = ();

#extract all filenames of protein complexes
$pathCofm = join '',$pathCofm,'*/*';
my @files = < $pathCofm >;

#number of cofm-files
#print "cofm-files: ", scalar(@files),"\n";

for(my $i =0; $i<scalar(@files); $i++){
	my $io = SBG::DomainIO::cofm->new(file=>$files[$i]);
	while(my $dom = $io->read){
		if(! defined $pdbIDs{lc $dom->pdbid}){
			$pdbIDs{lc $dom->pdbid} = {$dom->classification => 1};
		} else {
			if(! defined $pdbIDs{lc $dom->pdbid}{$dom->classification}){
				$pdbIDs{lc $dom->pdbid}{$dom->classification} = 1;
			} else {
				$pdbIDs{lc $dom->pdbid}{$dom->classification} += 1;
			}
		}
	}
}

#number of protein complexes
#print "PDB-IDs: ",scalar(keys %pdbIDs),"\n";

#match protein pairs based on number of domains with same classification
my %candidates=();
for my $a (keys %pdbIDs){
	$candidates{$a}=();
	for my $b (keys %pdbIDs){
		if($a ne $b){
			for my $class (keys %{$pdbIDs{$a}}){
				if(defined $pdbIDs{$b}{$class}){
					if(defined $candidates{$a}{$b}){
						$candidates{$a}{$b}+=min($pdbIDs{$a}{$class},$pdbIDs{$b}{$class});	
					} else {
						$candidates{$a}{$b}=min($pdbIDs{$a}{$class},$pdbIDs{$b}{$class});	
					}
				}
			}
		}
	}
}

#write candidates for each query to file
open FILE, ">./candidates" or die $!;

for my $query (sort keys %candidates){
	print FILE ("---",$query,"---",$/);
	for my $candidate (sort { $candidates{$query}{$b} <=> $candidates{$query}{$a}} keys %{$candidates{$query}}){
		print FILE ($candidate," ");#,$candidates{$query}{$candidate}," "); - don't print number of domains with same classification
	}
	print FILE ($/);
}

close FILE;


#returns minimum of a and b
sub min{
	my ($a, $b)=@_;
	if($a <= $b){
		return $a;
	} else {
		return $b;
	}
}


=head2 getDomains

 Function: fetches domains of a complex
 Example : 
 Returns : list of domain objects
 Args    : pdb-ID
 
 Employs the DomainIO module of sbglib to fetch the domains of a complex as represented in cofm-format. 
 
=cut
sub getDomains{
	my ($pathCofm, $pdbID) = @_;
	my @doms = ();
	#determine file names that match to pdb-ID
	my $path = join '', $pathCofm, substr($pdbID, 1, 2), '/',$pdbID,'-*.cofm';
	my @files = < $path >; 
	#fetch domains
	for my $file (@files){
		my $io = SBG::DomainIO::cofm->new(file=>$file);
		while(my $dom = $io->read){
			push @doms, $dom;
		}
	}
	#return domains
	return @doms;
}